<script setup>
import { onMounted, ref, watch } from 'vue'
import TdtMap from './components/TdtMap.vue'
import { sampleSourceData } from './mock/sampleData.js'
import baseConfig from './lib/defaultConfig.js'
import API_ENDPOINTS from './config/api.js'

const mapRef = ref(null)
const mapConfig = ref(baseConfig)
const mapData = ref([])
const loading = ref(false)

const resolveApiConfig = () => {
  const dataSource = mapConfig.value?.dataSource || {}
  if (dataSource.apiKey && API_ENDPOINTS[dataSource.apiKey]) {
    return API_ENDPOINTS[dataSource.apiKey]
  }
  return dataSource.api || null
}

const normalizeRecord = (item = {}) => {
  const lng =
    item.lng ??
    item.longitude ??
    item.lon ??
    item.lngLat?.lng ??
    item.position?.lng ??
    null
  const lat =
    item.lat ??
    item.latitude ??
    item.latit ??
    item.lngLat?.lat ??
    item.position?.lat ??
    null

  if (lng === null || lat === null) {
    return null
  }

  return {
    ...item,
    lng,
    lat,
    title: item.title ?? item.name ?? item.companyName ?? '',
    location: item.location ?? item.address ?? item.region ?? '',
    content: item.content ?? item.description ?? '',
  }
}

const fetchDataFromApi = async () => {
  const apiCfg = resolveApiConfig()
  if (!apiCfg?.url) {
    console.warn('[TdtMap Demo] API 配置缺失，回退到示例数据')
    mapData.value = sampleSourceData
    return
  }

  const method = (apiCfg.method || 'POST').toUpperCase()
  const headers = {
    'Content-Type': 'application/json',
    ...(apiCfg.headers || {}),
  }
  const payload = apiCfg.payload || {}

  const requestInit = {
    method,
    headers,
  }

  if (method !== 'GET') {
    requestInit.body = JSON.stringify(payload)
  }

  loading.value = true
  try {
    const response = await fetch(apiCfg.url, requestInit)
    if (!response.ok) {
      throw new Error(`请求失败：HTTP ${response.status}`)
    }
    const result = await response.json()
    console.log('[TdtMap Demo] API 返回结果', result)

    let rawData = []
    if (Array.isArray(result)) {
      rawData = result
    } else if (Array.isArray(result?.data)) {
      rawData = result.data
    } else if (Array.isArray(result?.data?.list)) {
      rawData = result.data.list
    } else if (Array.isArray(result?.data?.rows)) {
      rawData = result.data.rows
    }

    const normalized = rawData
      .map((item) => normalizeRecord(item))
      .filter((item) => item !== null)

    if (normalized.length === 0) {
      console.warn('[TdtMap Demo] API 数据未包含有效经纬度，使用空结果。')
    }

    mapData.value = normalized
  } catch (error) {
    console.error('[TdtMap Demo] 获取 API 数据失败：', error)
    mapData.value = []
  } finally {
    loading.value = false
  }
}

const loadData = async () => {
  const type = mapConfig.value?.dataSource?.type || 'mock'
  if (type === 'api') {
    await fetchDataFromApi()
  } else {
    mapData.value = sampleSourceData
  }
}

onMounted(loadData)

watch(
  () => mapConfig.value?.dataSource,
  () => {
    loadData()
  },
  { deep: true }
)
</script>

<template>
  <div class="map-wrapper">
    <TdtMap
      ref="mapRef"
      class="map"
      :config="mapConfig"
      :source-data="mapData"
      @markerClick="(payload) => console.log('markerClick', payload)"
      @error="(error) => console.error('Map error', error)"
      @ready="() => console.log('Tianditu map ready')"
    />
    <div v-if="loading" class="loading">数据加载中...</div>
  </div>
</template>

<style scoped>
.map-wrapper {
  position: relative;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  background: #050813;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 100%;
}

.loading {
  position: absolute;
  top: 16px;
  right: 20px;
  padding: 6px 12px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 6px;
  font-size: 12px;
  color: #fff;
  z-index: 1000;
  pointer-events: none;
}
</style>
